Amazon S3 Bucket Management with C#: Part 5 – Creating a Directory in a Bucket

Before getting started

Skill Level: Beginner

Assumptions:

  1. You already gone through Parts 1-4 of Managing Amazon AWS with C#.

Additional information: I sometimes cover small sub-topics in a post. Along with AWS, you will also be exposed to:

  • Rhyous.SimpleArgs

Step 1 – Add a CreateBucketDirectory method to BucketManager.cs

  1. Edit file called BucketManager.cs.
  2. Enter this new method:
            public static async Task CreateBucketDirectory(AmazonS3Client client, string bucketName, string directory)
            {
                var dirRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = directory + "/",
                    InputStream = new MemoryStream(new byte[0])
                };
                await client.PutObjectAsync(dirRequest);
                Console.WriteLine($"Created S3 bucket folder: {bucketName}/{directory}/");
            }
    

Note: Amazon S3 uses objects with a key ending in a / as a directory, so all we do is put a new empty object with a slash.

Step 2 – Update the Action Argument

We now need to make this method a valid action for the Action Argument.

  1. Edit the ArgsHandler.cs file to define an Action argument.
                        ...
                        AllowedValues = new ObservableCollection<string>
                        {
                            "CreateBucket",
                            "DeleteBucket",
                            "ListFiles",
                            "UploadFile",
                            "CreateBucketDirectory"
                        },
                        ...
    
    
    

Step 3 – Fix the parameter mismatch problem

In Part 4, we created a method to pass different parameters to different methods. Let’s use that to pass in the correct parameters.

            // Use the Custom or Common pattern
            CustomParameters.Add("UploadFile", new object[] { transferUtility, bucketName, Args.Value("File") });
            CustomParameters.Add("CreateBucketDirectory", new object[] { s3client, bucketName, Args.Value("Directory") });

You can now add a directory on S3, using C#.

Go to:

Return to: Managing Amazon AWS with C#

Leave a Reply

How to post code in comments?